﻿using AutoMapper;
using Infrastructure;
using SqlSugar;
using Standard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using YSL.Application.Ysl_Dto.Input.WorkOrder;
using YSL.Application.Ysl_Dto.Output;
using YSL_Domain.Model;

namespace YSL.Application.Services.WorkOrder
{
    public class WorkOrderService : IWorkOrderService
    {
        private readonly MesRepository<YSL_WORKORDER> _workOrderRepository;
        private readonly IMapper _mapper;



        public WorkOrderService(MesRepository<YSL_WORKORDER> workOrderRepository, IMapper mapper)
        {
            _workOrderRepository = workOrderRepository;
            _mapper = mapper;

        }

        public ApiResult<int> AddWorkOrder(AddWorkOrderInput input)
        {
            var model = _workOrderRepository.GetEntity(x => x.WORKORDERID == input.WORKORDERID);
            if (model != null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "工单已存在"
                };
            }

            var mapper = _mapper.Map<YSL_WORKORDER>(input);
            mapper.WORKORDERID = YitIdHelper.NextId().ToString();

            string datePart = DateTime.Now.ToString("yyyyMMdd");
            var todayStart = DateTime.Today;
            var todayEnd = todayStart.AddDays(1);

            // 查询当天最大 FILD1 值
            int maxField1 = _workOrderRepository.GetQueryable(x =>
                    x.CREATE_TIME >= todayStart && x.CREATE_TIME < todayEnd)
                .Max(x => (int?)x.FILD1) ?? 0;

            int nextSerial = maxField1 + 1;

            // 设置 CODEID 和 FILD1
            // mapper.CODEID = $"GD{datePart}{nextSerial:D4}";
            mapper.CODEID = input.CODEID;
            mapper.FILD1 = nextSerial;
            mapper.CREATE_TIME = DateTime.Now;
            mapper.ISDELETE = false;
            mapper.SOURCE_WORKER = $"MO{datePart}{nextSerial:D4}";
            mapper.LOCK_STATUE = "已解锁";
            mapper.PROCESS_PROGRESS = "0";

            var res = _workOrderRepository.Add(mapper);

            if (res > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.Success,
                    Message = "工单添加成功",
                    ResultData = res
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiCode.ParameterError,
                    Message = "工单添加失败",
                    ResultData = res
                };
            }
        }

        /// <summary>
        /// 删除工单（支持单个和批量）
        /// </summary>
        /// <param name="input">删除工单的输入参数，支持单个或多个工单ID</param>
        /// <returns>返回删除工单的结果</returns>
        public ApiResult<int> DeleteWorkOrder(DeleWorkOrderInput input)
        {
            // 收集所有要删除的工单ID
            var workOrderIds = new List<string>();
            if (!string.IsNullOrEmpty(input.WORKORDERID))
            {
                workOrderIds.Add(input.WORKORDERID);
            }
            if (input.WORKORDERIDS != null && input.WORKORDERIDS.Any())
            {
                workOrderIds.AddRange(input.WORKORDERIDS);
            }
            workOrderIds = workOrderIds.Distinct().ToList();

            if (!workOrderIds.Any())
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.ParameterError,
                    Message = "未提供工单ID",
                    ResultData = 0
                };
            }

            // 查询所有要删除的工单
            var models = _workOrderRepository.GetQueryable(x => workOrderIds.Contains(x.WORKORDERID)).ToList();
            if (!models.Any())
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.ParameterError,
                    Message = "未找到对应工单",
                    ResultData = 0
                };
            }

            // 标记为删除
            foreach (var model in models)
            {
                model.ISDELETE = true;
                model.LOCK_STATUE = "锁定";
            }

            // 批量更新
            var res = _workOrderRepository.BatchUpdate(models);
            //  _workOrderRepository.UpdateRange(models);

            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                Message = "删除工单成功",
                ResultData = res
            };
        }

        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns>返回工单列表的查询结果</returns>
        public ApiPaging<WorkOrderListOutput> GetWorkOrderList(GetWorkOrderListInput input)
        {
            ApiPaging<WorkOrderListOutput> result = new ApiPaging<WorkOrderListOutput>();
            var model = _workOrderRepository.GetQueryable(x => x.ISDELETE == false && x.LOCK_STATUE == "已解锁");
            if (input.WORKORDER_TYPE != null)
            {
                model = model.Where(x => x.WORKORDER_TYPE == input.WORKORDER_TYPE);
            }
            if (input.CODEID != null)
            {
                model = model.Where(x => x.CODEID == input.CODEID);
            }
            if (input.PRODUCTION_LINE != null)
            {
                model = model.Where(x => x.PRODUCTION_LINE == input.PRODUCTION_LINE);
            }
            result.TotalCount = model.Count();
            var mapper = _mapper.Map<List<WorkOrderListOutput>>(model.ToList());
            //分页   
            result.TotalPage = (int)Math.Ceiling(model.Count() * 1.0 / input.PageSize);
            result.PageDatas = mapper.OrderByDescending(x => x.WORKORDERID).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            result.Code = ApiCode.Success;
            result.Message = "查询工单列表";
            return result;

        }


        /// <summary>
        /// 更新工单
        /// </summary>
        /// <param name="input">更新工单的输入参数</param>
        /// <returns>返回更新工单的结果</returns>
        public ApiResult<int> UpdateWorkOrder(UpWorkOrderInput input)
        {
            var model = _workOrderRepository.GetEntity(x => x.WORKORDERID == input.WORKORDERID);
            ////映射修改
            var map = _mapper.Map(input, model);

            var res = _workOrderRepository.Update(map);
            if (res > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.Success,
                    Message = "更新成功",
                    ResultData = res
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.ParameterError,
                    Message = "修改失败",
                    ResultData = 0
                };
            }



        }

        /// <summary>
        /// 按月统计工单计划开始日期的总数量，返回每月统计列表
        /// </summary>
        public ApiResult<List<GetWorkOrderNumberListDto>> GetWorkOrderListNumber()
        {
            // 先查出所有未删除且已解锁且有开始时间的工单
            var list = _workOrderRepository.GetQueryable(x => x.ISDELETE == false && x.LOCK_STATUE == "已解锁" && x.START_TIME != null)
                .Select(x => new { x.START_TIME, x.NUMBER_COL })
                .ToList();

            // 在内存中按年月分组统计
            var result = list
                .GroupBy(x => new { Year = x.START_TIME.Value.Year, Month = x.START_TIME.Value.Month })
                .Select(g => new GetWorkOrderNumberListDto
                {
                    START_TIME = new DateTime(g.Key.Year, g.Key.Month, 1),
                    TotalNUMBER_COL = g.Sum(x => x.NUMBER_COL ?? 0)
                })
                .OrderBy(x => x.START_TIME)
                .ToList();
            return new ApiResult<List<GetWorkOrderNumberListDto>>
            {
                Code = ApiCode.Success,
                Message = "按月统计工单总数量成功",
                ResultData = result
            };
        }
    }
}

